import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

/*
* 图片选择组件
* */
const List<String> defautImages = [
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tdgve1j30ku0bsn75.jpg',
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2whp87sj30ku0bstec.jpg',
  'http://ww3.sinaimg.cn/large/006y8mN6ly1g6e2tl1v3bj30ku0bs77z.jpg',
];
//图片宽750px,高424px
var imageWidth = 750.0;
var imageHeight = 424.0;
var imageWidthHeightRatio = imageWidth / imageHeight;

class CommonImagePicker extends StatefulWidget {
  final ValueChanged<List<File>> onChange;

  const CommonImagePicker({Key key, this.onChange}) : super(key: key);

  @override
  _CommonImagePickerState createState() => _CommonImagePickerState();
}

class _CommonImagePickerState extends State<CommonImagePicker> {
  //存储图片列表
  List<File> files = [];

  _pickImage() async {
    var image = await ImagePicker.pickImage(source: ImageSource.gallery);
    if (null == image) return;
    setState(() {
      files = files..add(image);
    });
    //返回选中的图片列表
    if (widget.onChange != null) widget.onChange(files);
  }

  @override
  Widget build(BuildContext context) {
    //图片宽度
    var width = (MediaQuery.of(context).size.width - 10.0 * 4) / 3;
    var height = width / imageWidthHeightRatio;
    //添加图片按钮
    Widget addButton = GestureDetector(
      onTap: () {
        _pickImage();
      },
      behavior: HitTestBehavior.translucent,
      child: Container(
        width: width,
        height: height,
        color: Colors.grey,
        child: Center(
          child: Text(
            "＋",
            style: TextStyle(fontSize: 40, fontWeight: FontWeight.w100),
          ),
        ),
      ),
    );
    //添加的图片
    Widget wrapper(File file) {
      //使用Stack+Positioned实现删除按钮和图片的叠加
      return Stack(
        clipBehavior: Clip.none,//让溢出Stack部分仍然可见
        children: [
          Image.file(
            file,
            width: width,
            height: height,
            fit: BoxFit.cover,
          ),
          Positioned(//让里面的内容浮动起来
              right: -20,
              top: -20,
              child: IconButton(
                onPressed: (){
                  setState(() {
                    files = files..remove(file);
                  });
                  //返回选中的图片列表
                  if (widget.onChange != null) widget.onChange(files);
                },
                icon: Icon(
                  Icons.delete_forever,
                  color: Colors.red,
                ),
              ))
        ],
      );
    }

    //图片列表
    List<Widget> list = files.map((item) => wrapper(item)).toList()
      ..add(addButton);
    return Container(
      padding: EdgeInsets.all(10.0),
      child: Wrap(
        spacing: 10.0, //水平间距
        runSpacing: 10.0, //垂直间距
        children: list,
      ),
    );
  }
}
